/**
 * 加载进度管理器
 * 用于拖拽模型/节点组时显示加载进度
 * 优化版：按类型分类显示，避免创建大量DOM元素
 */

class LoadingProgressManager {
    constructor() {
        this.container = null;
        this.progressBar = null;
        this.progressText = null;
        this.statusText = null;
        this.isShowing = false;
        
        // 按类型分类的进度跟踪
        this.categories = {
            model: { name: '模型加载', total: 0, completed: 0, current: '' },
            hierarchy: { name: '节点创建', total: 0, completed: 0, current: '' },
            material: { name: '材质应用', total: 0, completed: 0, current: '' }
        };
    }

    /**
     * 初始化进度条UI
     */
    init() {
        if (this.container) return;

        // 创建容器
        this.container = document.createElement('div');
        this.container.className = 'loading-progress-overlay';
        this.container.innerHTML = `
            <div class="loading-progress-modal">
                <div class="loading-progress-header">
                    <span class="loading-spinner"></span>
                    <h3>正在加载模型...</h3>
                </div>
                <div class="loading-progress-body">
                    <div class="progress-bar-container">
                        <div class="progress-bar"></div>
                    </div>
                    <div class="progress-text">0%</div>
                    <div class="status-text">准备加载...</div>
                    <div class="category-details"></div>
                </div>
            </div>
        `;
        document.body.appendChild(this.container);

        // 获取元素引用
        this.progressBar = this.container.querySelector('.progress-bar');
        this.progressText = this.container.querySelector('.progress-text');
        this.statusText = this.container.querySelector('.status-text');
        this.categoryContainer = this.container.querySelector('.category-details');
    }

    /**
     * 显示进度条
     */
    show() {
        this.init();
        
        // 重置所有分类
        Object.keys(this.categories).forEach(key => {
            this.categories[key].total = 0;
            this.categories[key].completed = 0;
            this.categories[key].current = '';
        });
        
        this.isShowing = true;
        this.container.style.display = 'flex';
        this.updateDisplay();
        console.log(`📊 [LoadingProgress] 显示进度条`);
    }

    /**
     * 隐藏进度条
     */
    hide() {
        if (!this.container || !this.isShowing) return;
        
        this.container.style.display = 'none';
        this.isShowing = false;
        console.log('✅ [LoadingProgress] 隐藏进度条');
    }

    /**
     * 设置分类的总数
     * @param {string} type - 类型 ('model' | 'hierarchy' | 'material')
     * @param {number} total - 总数
     */
    setCategoryTotal(type, total) {
        if (this.categories[type]) {
            this.categories[type].total = total;
            this.categories[type].completed = 0;
            console.log(`📊 [LoadingProgress] ${this.categories[type].name}: ${total} 项`);
            this.updateDisplay();
        }
    }

    /**
     * 更新分类的当前项
     * @param {string} type - 类型
     * @param {string} itemName - 当前项名称
     */
    updateCategoryItem(type, itemName) {
        if (this.categories[type]) {
            this.categories[type].current = itemName;
            this.updateDisplay();
        }
    }

    /**
     * 完成分类中的一项
     * @param {string} type - 类型
     */
    incrementCategory(type) {
        if (this.categories[type]) {
            this.categories[type].completed++;
            console.log(`✅ [LoadingProgress] ${this.categories[type].name}: ${this.categories[type].completed}/${this.categories[type].total}`);
            this.updateDisplay();
            
            // 检查是否全部完成
            this.checkComplete();
        }
    }

    /**
     * 检查是否全部完成
     */
    checkComplete() {
        const allComplete = Object.values(this.categories).every(cat => 
            cat.total === 0 || cat.completed >= cat.total
        );
        
        if (allComplete && this.isShowing) {
            const totalItems = Object.values(this.categories).reduce((sum, cat) => sum + cat.total, 0);
            if (totalItems > 0) {
                setTimeout(() => {
                    this.hide();
                }, 500);
            }
        }
    }

    /**
     * 计算总体进度
     */
    calculateProgress() {
        let totalItems = 0;
        let completedItems = 0;
        
        Object.values(this.categories).forEach(cat => {
            totalItems += cat.total;
            completedItems += cat.completed;
        });
        
        if (totalItems === 0) return 0;
        return Math.round((completedItems / totalItems) * 100);
    }

    /**
     * 更新显示
     */
    updateDisplay() {
        if (!this.isShowing) return;
        
        // 更新总体进度
        const progress = this.calculateProgress();
        this.progressBar.style.width = `${progress}%`;
        this.progressText.textContent = `${progress}%`;
        
        // 计算总项数
        let totalItems = 0;
        let completedItems = 0;
        Object.values(this.categories).forEach(cat => {
            totalItems += cat.total;
            completedItems += cat.completed;
        });
        
        if (totalItems > 0) {
            this.statusText.textContent = `正在加载 ${completedItems}/${totalItems} 项...`;
        } else {
            this.statusText.textContent = '准备加载...';
        }
        
        // 更新分类详情
        this.updateCategoryDisplay();
    }

    /**
     * 更新分类详情显示
     */
    updateCategoryDisplay() {
        if (!this.categoryContainer) return;
        
        const categoryItems = [];
        
        Object.entries(this.categories).forEach(([type, cat]) => {
            if (cat.total === 0) return;
            
            const progress = cat.total > 0 ? Math.round((cat.completed / cat.total) * 100) : 0;
            const icon = this.getCategoryIcon(type, cat.completed >= cat.total);
            const statusClass = cat.completed >= cat.total ? 'category-completed' : 'category-loading';
            
            categoryItems.push(`
                <div class="category-item ${statusClass}">
                    <div class="category-header">
                        <span class="category-icon">${icon}</span>
                        <span class="category-name">${cat.name}</span>
                        <span class="category-count">${cat.completed}/${cat.total}</span>
                    </div>
                    ${cat.current && cat.completed < cat.total ? `<div class="category-current">当前: ${cat.current}</div>` : ''}
                </div>
            `);
        });
        
        this.categoryContainer.innerHTML = categoryItems.join('');
    }

    /**
     * 获取分类图标
     */
    getCategoryIcon(type, completed) {
        if (completed) return '✅';
        
        if (type === 'model') return '📦';
        if (type === 'material') return '🎨';
        if (type === 'hierarchy') return '🌳';
        return '⏳';
    }

    /**
     * 增加分类总数
     */
    addCategoryTotal(type, count) {
        if (this.categories[type]) {
            this.categories[type].total += count;
            this.updateDisplay();
        }
    }
}

// 创建全局单例
const loadingProgressManager = new LoadingProgressManager();
window.loadingProgressManager = loadingProgressManager;

export default loadingProgressManager;
